package com.qiaofang.applet.service.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.context.QfContext;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.PageDTO;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.dto.EmployeeEntrustQueryDto;
import com.qiaofang.applet.service.other.service.dto.PropertyEntrustDto;
import com.qiaofang.applet.service.other.service.dto.PropertyEntrustQueryV1Dto;
import com.qiaofang.applet.service.other.service.dto.PropertyEntrustRequestDto;
import com.qiaofang.applet.service.property.service.PropertyEntrustService;
import com.qiaofang.applet.service.property.service.dto.NewEntrustSimpleDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: youqing.yang
 * @Create: 2020/12/23 19:29
 * @Description:
 **/
@Service
@Slf4j
public class PropertyEntrustServiceImpl implements PropertyEntrustService {

    private static RestTemplate restTemplate = new RestTemplate();

    private static final String PROPERTY_ENTRUST = "/api/dataprocessing/propertyEntrust/getPropertyEntrustPage";

    private static final String ACCEPT_ENTRUST_MYSELF = "/api/dataprocessing/propertyEntrust/acceptEntrustMyself";

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Override
    public Page<PropertyEntrustDto> getPropertyEntrustPage(PropertyEntrustQueryV1Dto query, Pageable pageable) {

        Corporation corporation = corporationService.getCorporationByCorporationCode(QfContextHolder.getContext().getCorporationCode());
        if (corporation == null) {
            throw new BusinessException("集团不存在");
        }
        String companyUuid = cityCompanyService.getCompanyUuid(query.getCityCode(), QfContextHolder.getContext().getCorporationCode());
        HttpHeaders headers = getHeaders(companyUuid, corporation.getPullAppId(), corporation.getPullAppKey());
        PropertyEntrustRequestDto requestParam = new PropertyEntrustRequestDto();
        BeanUtils.copyProperties(query, requestParam);
        if (StringUtils.isNotEmpty(query.getEmployeeUniqueUuidUuid())){
            String employeeUuid = query.getEmployeeUniqueUuidUuid().replaceAll(companyUuid + "_", "");
            requestParam.setEmployeeUuid(employeeUuid);
//            requestParam.setEntrustStatus("0");
        }
        PageDTO pageDTO = new PageDTO();
        pageDTO.setPageNum(pageable.getPageNumber() + 1);
        pageDTO.setPageSize(pageable.getPageSize());
        requestParam.setPageDTO(pageDTO);

        Map<String, Object> map = new HashMap<>();
        map.put("param", requestParam);
        map.put("page", pageDTO);
        JSONObject result = null;
        try {
            result = restTemplate.postForEntity(corporation.getPullDomain() + PROPERTY_ENTRUST, new HttpEntity<>(map, headers), JSONObject.class).getBody();
        } catch (RestClientException e) {
            throw new BusinessException(e);
        }
        log.info("getMyEdeals http result:{}", result);
        PageImpl<PropertyEntrustDto> propertyEntrustDtoPage = null;
        if (result.getInteger("responseCode") == 1) {
            JSONObject resultJSONObject = result.getJSONObject("data");
            String cityName = cityCompanyService.getCityByCitycode(query.getCityCode());
            List<PropertyEntrustDto> items = resultJSONObject.getJSONArray("items").toJavaList(PropertyEntrustDto.class).stream().map(item -> {
                item.setCityName(cityName);
                return item;
            }).collect(Collectors.toList());
            propertyEntrustDtoPage = new PageImpl<>(items, pageable, resultJSONObject.getLong("count"));
            return propertyEntrustDtoPage;
        }else {
            throw new BusinessException(result.getString("responseMessage"));
        }
    }

    @Override
    public Page<PropertyEntrustDto> getEmployeeEntrusts(EmployeeEntrustQueryDto queryDto, Pageable pageable) {
        PropertyEntrustQueryV1Dto queryV1Dto = new PropertyEntrustQueryV1Dto();
        queryV1Dto.setCityCode(QfContextHolder.getContext().getCityCode());
        queryV1Dto.setEntrustStatus(queryDto.getEntrustStatus());
        queryV1Dto.setEmployeeUniqueUuidUuid(queryDto.getEmployeeUniqueUuidUuid());
        return getPropertyEntrustPage(queryV1Dto, pageable);
    }

    @Override
    public List<NewEntrustSimpleDto> newEntrustList(String employeeUniqueUuid) {
        EmployeeEntrustQueryDto queryDto = new EmployeeEntrustQueryDto();
        queryDto.setEmployeeUniqueUuidUuid(employeeUniqueUuid);
        queryDto.setEntrustStatus("0");
        List<PropertyEntrustDto> content = getEmployeeEntrusts(queryDto, PageRequest.of(0, 4)).getContent();
        List<NewEntrustSimpleDto> result = new ArrayList<>(content.size());
        for (PropertyEntrustDto propertyEntrustDto : content) {
            NewEntrustSimpleDto simpleDto = new NewEntrustSimpleDto();
            StringBuilder sb = new StringBuilder(propertyEntrustDto.getEstateName());
            sb.append(" " + propertyEntrustDto.getBuildingValue());
            if ("出售".equals(propertyEntrustDto.getTradeType())){
                sb.append(" 期望" + propertyEntrustDto.getSalePrice());
                simpleDto.setBusinessType(BusinessConstants.SALE_PROPERTY.getCode());
            }else {
                sb.append(" 期望" + propertyEntrustDto.getRentPrice());
                simpleDto.setBusinessType(BusinessConstants.RENT_PROPERTY.getCode());
            }
            simpleDto.setShowInfo(sb.toString());
            result.add(simpleDto);
        }
        return result;
    }

    @Override
    public void acceptEntrustMyself(Long propertyEntrustId) {
        QfContext context = QfContextHolder.getContext();
        Corporation corporation = corporationService.getCorporationByCorporationCode(context.getCorporationCode());
        if (corporation == null) {
            throw new BusinessException("集团不存在");
        }
        String companyUuid = cityCompanyService.getCompanyUuid(context.getCityCode(), context.getCorporationCode());
        HttpHeaders headers = getHeaders(companyUuid, corporation.getPullAppId(), corporation.getPullAppKey());
        Map<String, Object> map = new HashMap<>();
        map.put("param", propertyEntrustId);
        JSONObject result = null;
        try {
            result = restTemplate.postForEntity(corporation.getPullDomain() + ACCEPT_ENTRUST_MYSELF, new HttpEntity<>(map, headers), JSONObject.class).getBody();
        } catch (RestClientException e) {
            throw new BusinessException(e);
        }
        log.info("getMyEdeals http result:{}", result);
        if (result.getInteger("responseCode") == 1) {
            Integer i = result.getInteger("data");
            if (i == 0){
                throw new BusinessException("委托状态已更改");
            }
        }else {
            throw new BusinessException(result.getString("responseMessage"));
        }
    }

    private HttpHeaders getHeaders(String companyUuid, String appId, String appKey) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", appId);
        headers.add("X-AUTH-KEY", appKey);
        headers.add("companyUuid", companyUuid);
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

}
